<?php

namespace App\Modules\Rebate;


use App\Exceptions\StandardException;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\User\Models\User;
use Illuminate\Support\Facades\Log;

class Manager
{
    public static function rebateFinish(User $user, $money, &$orderId, &$rebateId)
    {
        $rebate = Rebate::query()
            ->where('user_id', $user->id)
            ->where('status', Rebate::STATUS_ISSUED)
            ->orderBy('id')
            ->limit(50)
            ->get();
        if ($rebate->isEmpty()) {
            return ;
        }
        $rebate->each(function ($item) use (&$money, &$orderId, &$rebateId) {
                $rebateId[] = $item->id;
                $orderId[] = $item->link_id;
                if ($money > 0 && $money >= $item->money) {
                    $item->status = Rebate::STATUS_FINISH;
                    $item->withdrawal_status = Rebate::WITHDRAWAL_STATUS_PENDING;
                    $item->save();
                    $money -= $item->money;
                } else {
                    throw new StandardException("提现金额错误");
                }
            });
        if ($money > 0) {
            self::rebateFinish($user, $money,$orderId,$rebateId);
        }
        return ;
    }
}
